@using Microsoft.AspNetCore.Http
@inject IInstallationService InstallationService
@inject IJSRuntime JSRuntime
@inject SiteState SiteState
@inject IServiceProvider ServiceProvider

@if (_initialized)
{
    @if (!_installation.Success)
    {
        <Installer />
    }
    else
    {
        @if (string.IsNullOrEmpty(_installation.Message))
        {
            <div style="@_display">
                <CascadingAuthenticationState>
                    <CascadingValue Value="@PageState">
                        <SiteRouter Runtime="@Runtime" RenderMode="@RenderMode" VisitorId="@VisitorId" OnStateChange="@ChangeState" />
                    </CascadingValue>
                </CascadingAuthenticationState>
            </div>
        }
        else
        {
            <div class="app-alert">
                @_installation.Message
            </div>
        }
    }
}

@code {
    [Parameter]
    public string AntiForgeryToken { get; set; }

    [Parameter]
    public string Runtime { get; set; }

    [Parameter]
    public string RenderMode { get; set; }

    [Parameter]
    public int VisitorId { get; set; }

    [Parameter]
    public string RemoteIPAddress { get; set; }

    [Parameter]
    public string AuthorizationToken { get; set; }

    private bool _initialized = false;
    private string _display = "display: none;";
    private Installation _installation = new Installation { Success = false, Message = "" };

    private PageState PageState { get; set; }

    private IHttpContextAccessor accessor;

    protected override async Task OnParametersSetAsync()
    {
        SiteState.RemoteIPAddress = RemoteIPAddress;
        SiteState.AntiForgeryToken = AntiForgeryToken;
        SiteState.AuthorizationToken = AuthorizationToken;

        accessor = (IHttpContextAccessor)ServiceProvider.GetService(typeof(IHttpContextAccessor));
        if (accessor != null)
        {
            SiteState.IsPrerendering = !accessor.HttpContext.Response.HasStarted;
        }
        else
        {
            SiteState.IsPrerendering = true;
        }

        _installation = await InstallationService.IsInstalled();
        if (_installation.Alias != null)
        {
            SiteState.Alias = _installation.Alias;
        }
        _initialized = true;
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            // prevents flash on initial page load
            _display = "";
            StateHasChanged();
        }
    }

    private void ChangeState(PageState pageState)
    {
        PageState = pageState;
        StateHasChanged();
    }
}
